﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using 软件发布平台.ViewModel;
using MaterialDesignThemes.Wpf;
using MengXunAppTool.BLL;
using MengXunAppTool.DAL;
using MengXunAppTool.Helper;
using System.Text.RegularExpressions;
using System.Windows.Interop;
using System.Net.Sockets;

namespace 软件发布平台.View
{
    /// <summary>
    /// UserControlRelease.xaml 的交互逻辑
    /// </summary>
    public partial class ReleaseView : System.Windows.Controls.UserControl
    {
        private FtpBLL ftpBLL = new FtpBLL();
        private UIBLL uiBLL = null;
        private VerDAL verDAL = new VerDAL();
        private ShenPiDAL shenPiDAL = new ShenPiDAL();
        private ConfigHelper configHelper = new ConfigHelper();
        public ViewModel.ReleaseViewModel viewModel = new ViewModel.ReleaseViewModel();
        public MainWindow mainWindow = null;
        public ReleaseView()
        {
            //shenPiDAL.InitCxUsers();
            InitializeComponent();
            this.DataContext = viewModel;
            uiBLL = new UIBLL(Bar, BarText, BtnRelease);
            viewModel.ReleaseUsers = shenPiDAL.GetReleaseUsers();
            viewModel.CheckUsers = shenPiDAL.GetCheckUsers();

            viewModel.Temps = shenPiDAL.GetTemps();
            viewModel.Temps.Add("ALL");
            viewModel.Temp = "ALL";
            //check.IsDropDownOpen = true;
        }
        public string basePath = "";
        public string exeBasePath = "";
        public string exePath = "";
        public string exeZip = "";
        public string codeZip = "";
        public List<FileInfo> exeFiles = new List<FileInfo>();
        public List<FileInfo> files = new List<FileInfo>();
        public List<string> configFiles = new List<string>();
        public List<string> removeFiles = new List<string>();
        public List<string> removeExeFiles = new List<string>();
        public List<string> pushUsers = new List<string>();
        public List<string> names = new List<string>();
        #region 发布
        private void BtnSelect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FolderHelper dialog = new FolderHelper();
                if (dialog.ShowDialog(((HwndSource)PresentationSource.FromVisual(this)).Handle) == true)
                {
                    basePath = dialog.FileName;
                    viewModel.Items.Clear();
                    files.Clear();
                    exeFiles.Clear();
                    removeExeFiles.Clear();
                    removeFiles.Clear();
                    configFiles.Clear();
                    exePath = "";
                    List<CheckBoxTreeViewModel> treeViewModels = new List<CheckBoxTreeViewModel>();
                    viewModel.InitTree(basePath, files, treeViewModels, removeFiles, configFiles, exePath);
                    viewModel.Items = treeViewModels;
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        private void BtnRelease_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (TbxVer1.Text == "" || TbxVer2.Text == "" || CbxCus.Text == "" || CbxName.Text == "" || CbxPro.Text == ""
                    || TbxLog.Text == "")
                {
                    HandyControl.Controls.Growl.Warning("请完善上传信息！");
                    return;
                }
                viewModel.IsGuDingLuJing = false;
                if (string.IsNullOrEmpty(viewModel.GuDingLuJing) == false)
                {
                    viewModel.IsGuDingLuJing = true;
                    if (viewModel.GuDingLuJing.Contains(":\\") == false)
                    {
                        HandyControl.Controls.Growl.Warning("本地路径填写有误！");
                        return;
                    }
                }
                if (viewModel.FbUser == "" || viewModel.ReleaseUsers.Contains(viewModel.FbUser) == false)
                {
                    HandyControl.Controls.Growl.Warning("发布人填写有误！");
                    return;
                }
                if (viewModel.IsGuDingLuJing && viewModel.IsShenPi)
                {
                    HandyControl.Controls.Growl.Warning("指定本地路径时无法进行审批！");
                    return;
                }
                if (viewModel.IsShenPi &&( viewModel.CsUser == "" || viewModel.SpUser == "" ))
                {
                    HandyControl.Controls.Growl.Warning("审批填写有误！");
                    return;
                }
                if (viewModel.IsTuiSong && (pushUsers.Count == 0))
                {
                    HandyControl.Controls.Growl.Warning("推送填写有误！");
                    return;
                }
                string folder = "发布软件";

                Sql3Helper.MX_AppVerRecord mX_VerRecord = GetVerRecordModel(folder);
                if (CbFile.IsChecked == true)
                {
                    mX_VerRecord.ExePath = "\\OpenDirec.exe";
                    File.Copy(Environment.CurrentDirectory + "\\平台上传工具\\OpenDirec.exe", basePath + "\\OpenDirec.exe",true);
                    files.Add(new FileInfo(basePath + "\\OpenDirec.exe"));
                }
                switch (CbxLogin.Text)
                {
                    case "无": mX_VerRecord.Login = ""; break;
                    case "MES通用": mX_VerRecord.Login = "http://192.168.2.23:9213/integrate/login/queryGenerLogin"; break;
                    case "中移专用": mX_VerRecord.Login = "http://192.168.2.23:9213/integrate/login"; break;
                    case "工号": mX_VerRecord.Login = "http://192.168.2.23:9213/integrate/login/findByUserName?userName="; break;
                    default:
                        break;
                }
                if (string.IsNullOrEmpty(mX_VerRecord.ExePath))
                {
                    HandyControl.Controls.Growl.Warning("请先双击选中启动文件！");
                    return;
                }
                if (verDAL.IsDuplicate(mX_VerRecord))
                {
                    HandyControl.Controls.Growl.Warning("发现同名同版本软件！");
                    return;
                }
                var dialog = HandyControl.Controls.MessageBox.Show("启动文件确认！\r\n"+ mX_VerRecord.ExePath,button:MessageBoxButton.YesNo,icon:MessageBoxImage.Question);
                bool? isCode = CbCode.IsChecked;
                if (dialog == MessageBoxResult.Yes)
                {
                    new Thread((Action) =>
                    {
                        try
                        {
                            uiBLL.HideButton();
                            uiBLL.SetBarValue(0);
                            if (isCode == false)
                            {
                                exeFiles = files;
                                bool isUpZipOk = UpExeZip(folder, mX_VerRecord, ftpBLL);
                                if (!isUpZipOk)
                                {
                                    uiBLL.SetBarValue(0);
                                    uiBLL.ShowButton();
                                    HandyControl.Controls.Growl.Warning("上传失败！");
                                }
                            }
                            else
                            {
                                //todo 源代码上传
                                bool isUpZipOk = UpCodeZip(folder, mX_VerRecord, ftpBLL);
                                if (!isUpZipOk)
                                {
                                    uiBLL.SetBarValue(0);
                                    uiBLL.ShowButton();
                                    HandyControl.Controls.Growl.Warning("上传失败！");
                                }
                            }

                            bool isInsertOk = verDAL.InsertMX_AppVerRecord(mX_VerRecord);
                            if (!isInsertOk)
                            {
                                uiBLL.SetBarValue(0);
                                uiBLL.ShowButton();
                                HandyControl.Controls.Growl.Warning("上传数据库失败！");
                                return;
                            }
                            uiBLL.ShowButton();
                            if (viewModel.IsShenPi == true)
                            {
                                //todo 推送
                                string msg = $"软件平台通知：\r\n\r\n{mX_VerRecord.Customer}\r\n{mX_VerRecord.Product}\r\n{mX_VerRecord.AppName}{mX_VerRecord.Version}\r\n\r\n{mX_VerRecord.ReleaseLog}\r\n\r\n已由{mX_VerRecord.ReleaseUser}发布\r\n待{mX_VerRecord.CheckUser1}审批";
                                string err = "";
                                List<string> ids = new List<string> { shenPiDAL.GetId(mX_VerRecord.CheckUser1), shenPiDAL.GetId(mX_VerRecord.ReleaseUser) };

                                bool send = MesTool.UserBLL.SendMsg(msg, ref err, ids);
                                if (send == false)
                                {
                                    HandyControl.Controls.Growl.Warning("推送失败：\r\n" + err);
                                    return;
                                }
                            }
                            if (viewModel.IsTuiSong == true && viewModel.IsShenPi == false)
                            {
                                //todo 推送
                                string msg = $"软件平台通知：\r\n\r\n{mX_VerRecord.Customer}\r\n{mX_VerRecord.Product}\r\n{mX_VerRecord.AppName}{mX_VerRecord.Version}\r\n\r\n{mX_VerRecord.ReleaseLog}\r\n\r\n已由{mX_VerRecord.ReleaseUser}发布\r\n可下载使用";
                                string err = "";
                                List<string> ids = new List<string> { shenPiDAL.GetId(mX_VerRecord.ReleaseUser) };
                                foreach (var item in mX_VerRecord.PushUser.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    ids.Add(shenPiDAL.GetId(item));
                                }
                                bool send = MesTool.UserBLL.SendMsg(msg, ref err, ids);
                                if (send == false)
                                {
                                    HandyControl.Controls.Growl.Warning("推送失败：\r\n" + err);
                                    return;
                                }
                            }
                            HandyControl.Controls.Growl.Success("上传成功！");
                            File.Delete(basePath + "\\OpenDirec.exe");
                            File.Delete(exeZip);
                            if (codeZip != "" && File.Exists(codeZip))
                            {
                                File.Delete(codeZip);
                            }
                            mainWindow.appRecordView.Dispatcher.Invoke(() =>
                            {
                                mainWindow.appRecordView.InitRecord();
                            });
                        }
                        catch (Exception ee)
                        {
                            uiBLL.SetBarValue(0);
                            uiBLL.ShowButton();
                            HandyControl.Controls.Growl.Error(ee.Message.ToString());
                            LogHelper.WriteLog(ee.ToString());
                        }

                    }).Start();
                }
            }
            catch (Exception ee)
            {
                uiBLL.SetBarValue(0);
                uiBLL.ShowButton();
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }

        }
        private void CbNew_Checked(object sender, RoutedEventArgs e)
        {
            CbxCus.IsEditable = true;
            CbxPro.IsEditable = true;
            CbxName.IsEditable = true;
            CbxCus.Text = "";
            CbxPro.Text = "";
            CbxName.Text = "";
        }

        private void CbNew_Unchecked(object sender, RoutedEventArgs e)
        {
            CbxCus.IsEditable = false;
            CbxPro.IsEditable = false;
            CbxName.IsEditable = false;
        }

        private void CbxCus_DropDownOpened(object sender, EventArgs e)
        {
            try
            {
                CbxCus.ItemsSource = verDAL.GetCustomers();
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }

        }

        private void CbxPro_DropDownOpened(object sender, EventArgs e)
        {
            try
            {
                if (CbxCus.Text != "")
                {
                    CbxPro.ItemsSource = verDAL.GetProducts(CbxCus.Text);
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        private void CbxName_DropDownOpened(object sender, EventArgs e)
        {
            try
            {
                if (CbxCus.Text != "" && CbxPro.Text != "")
                {
                    CbxName.ItemsSource = verDAL.GetAppNames(CbxCus.Text, CbxPro.Text);
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        //private void CbxUser_DropDownOpened(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        CbxFbUser.ItemsSource = verDAL.GetReleaseUsers();
        //    }
        //    catch (Exception ee)
        //    {
        //        ShowMessage("错误！", ee.Message.ToString());
        //        LogHelper.WriteLog(ee.ToString() );
        //    }
        //}

        //private void CbxUser_DropDownClosed(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if (CbxName.Text == "" || CbxPro.Text == "" || CbxCus.Text == "" )
        //        {
        //            return;
        //        }
        //        if (CbNew.IsChecked == false)
        //        {
        //            string lastVer = verDAL.GetLastVer(CbxCus.Text, CbxPro.Text, CbxName.Text);
        //            double ver = double.Parse(lastVer.Replace("V", "")) + 0.1;
        //            TbxVer1.Text = ver.ToString().Split('.')[0];
  
        //            if (ver.ToString().Contains("."))
        //            {
        //                TbxVer2.Text = ver.ToString().Split('.')[1];
        //            }
        //            else
        //            {
        //                TbxVer2.Text = "0";
        //            }
        //        }
        //        else
        //        {
        //            TbxVer1.Text = "1";
        //            TbxVer2.Text = "0";
        //        }
        //    }
        //    catch (Exception ee)
        //    {
        //        ShowMessage("错误！", ee.Message.ToString());
        //        LogHelper.WriteLog(ee.ToString() );
        //    }
        //}

        public CheckBoxTreeViewModel SelectTreeViewModel;
        private void Tree_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //判断是否选中节点
                TreeViewItem target = GetNearestContainer(e.OriginalSource as UIElement);
                if (target != null)
                {
                    SelectTreeViewModel = target.Header as CheckBoxTreeViewModel;
                    //实例化菜单
                    System.Windows.Controls.ContextMenu cm = this.FindResource("cmButton") as System.Windows.Controls.ContextMenu;
                    //目标
                    cm.PlacementTarget = sender as TreeViewItem;
                    //位置
                    cm.Placement = PlacementMode.MousePoint;
                    //显示菜单
                    cm.IsOpen = true;
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        public void RemoveNodes(object sender, RoutedEventArgs e)
        {
            try
            {
                if (SelectTreeViewModel != null)
                {
                    removeFiles.Add(SelectTreeViewModel.Path);
                    viewModel.Items.Clear();
                    files.Clear();
                    List<CheckBoxTreeViewModel> treeViewModels = new List<CheckBoxTreeViewModel>();
                    viewModel.InitTree(basePath, files, treeViewModels, removeFiles, configFiles, exePath);
                    viewModel.Items = treeViewModels;
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        public TreeViewItem GetNearestContainer(UIElement element)
        {
            // 沿着元素树向上走到最近的树视图项。
            TreeViewItem container = element as TreeViewItem;
            while ((container == null) && (element != null))
            {
                element = VisualTreeHelper.GetParent(element) as UIElement;
                container = element as TreeViewItem;
            }
            return container;
        }
        CheckBoxTreeViewModel LastSelectModel;
        private void Tree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                TreeViewItem target = GetNearestContainer(e.OriginalSource as UIElement);
                if (target != null)
                {
                    target.IsSelected = true;
                    CheckBoxTreeViewModel SelectModel = target.Header as CheckBoxTreeViewModel;
                    if (SelectModel != null)
                    {
                        if (SelectModel.Path.Substring(SelectModel.Path.Length - 4).Equals(".exe"))
                        {
                            if (LastSelectModel != null)
                            {
                                LastSelectModel.ForeColor = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                            }
                            SelectModel.ForeColor = new SolidColorBrush(Color.FromRgb(50, 200, 50));
                            exePath = SelectModel.Path;
                            LastSelectModel = SelectModel;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }

        private void TbxVer1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = !(e.Key == Key.NumPad0 || e.Key == Key.NumPad5 ||
                        e.Key == Key.NumPad1 || e.Key == Key.NumPad6 ||
                        e.Key == Key.NumPad2 || e.Key == Key.NumPad7 ||
                        e.Key == Key.NumPad3 || e.Key == Key.NumPad8 ||
                        e.Key == Key.NumPad4 || e.Key == Key.NumPad9);
            if (e.Key == Key.Back)  //允许输入回退键
            {
                e.Handled = false;
            }
        }
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem target = GetNearestContainer(e.OriginalSource as UIElement);
                if (target != null)
                {
                    CheckBoxTreeViewModel CheckModel = target.Header as CheckBoxTreeViewModel;
                    if (CheckModel!=null)
                    {
                        configFiles.Add(CheckModel.Path);
                        TbxConfig.Text = string.Join("\r\n", configFiles.Select(o=>System.IO.Path.GetFileName(o)));
                    }
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString());
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem target = GetNearestContainer(e.OriginalSource as UIElement);
                if (target != null )
                {
                    CheckBoxTreeViewModel CheckModel = target.Header as CheckBoxTreeViewModel;
                    if (CheckModel != null)
                    {
                        configFiles.Remove(CheckModel.Path);
                        TbxConfig.Text = string.Join("\r\n", configFiles.Select(o => System.IO.Path.GetFileName(o)));
                    }
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString() );
            }
        }
        private void CbxCus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CbxPro.Text = "";
            CbxName.Text = "";
            TbxVer1.Text = "1";
            TbxVer2.Text = "0";
        }

        private void CbxPro_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CbxName.Text = "";
            TbxVer1.Text = "1";
            TbxVer2.Text = "0";
        }

        private void CbxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TbxVer1.Text = "1";
            TbxVer2.Text = "0";
            if (CbNew.IsChecked == false && CbxName.SelectedItem != null)
            {
                var lastVer = verDAL.GetLastApp(CbxCus.Text, CbxPro.Text, CbxName.SelectedItem.ToString());
                if (lastVer != null)
                {
                    //viewModel.FbUser = lastVer.ReleaseUser;
                    viewModel.SpUser = lastVer.CheckUser1;
                    viewModel.CsUser = lastVer.CheckUser2;
                    double ver = double.Parse(lastVer.Version.Replace("V", "")) + 0.1;
                    TbxVer1.Text = ver.ToString().Split('.')[0];

                    if (ver.ToString().Contains("."))
                    {
                        TbxVer2.Text = ver.ToString().Split('.')[1];
                    }
                    else
                    {
                        TbxVer2.Text = "0";
                    }
                }
            }
        }
        private Sql3Helper.MX_AppVerRecord GetVerRecordModel(string folder)
        {
            Sql3Helper.MX_AppVerRecord mX_VerRecord = new Sql3Helper.MX_AppVerRecord()
            {
                AppName = CbxName.Text,
                Version = "V" + TbxVer1.Text + "." + TbxVer2.Text,
                Customer = CbxCus.Text,
                Product = CbxPro.Text,
                LocalPath = viewModel.GuDingLuJing,
                ReleaseUser = viewModel.FbUser,
                CheckUser1 = viewModel.IsShenPi ? viewModel.SpUser : "",
                CheckUser2 = viewModel.IsShenPi ? viewModel.CsUser : "",
                PushUser = viewModel.IsTuiSong ? string.Join(",", pushUsers.ToArray()) : "",
                ReleaseLog = TbxLog.Text,
                Enable = "True",
                FtpPath = folder + "\\" + CbxCus.Text + "\\" + CbxPro.Text + "\\" + CbxName.Text + "\\" + CbxName.Text + "V" + TbxVer1.Text + "." + TbxVer2.Text + ".zip"
            };
            if (mX_VerRecord.Customer == "盟讯" && mX_VerRecord.Product == "通用" && (mX_VerRecord.AppName.Contains("软件发布平台") || mX_VerRecord.AppName.Contains("软件运行平台")))
            {
                mX_VerRecord.Enable="False";
            }
            string path = basePath;
            if (CbCode.IsChecked == true)
            {
                path = exeBasePath;
            }
            foreach (var item in configFiles)
            {
                mX_VerRecord.ConfigPathList += (item.Replace(path, "") + ";");
            }
            mX_VerRecord.ExePath = exePath.Replace(path, "");
            return mX_VerRecord;
        }        
        public bool UpExeZip(string folder, Sql3Helper.MX_AppVerRecord mX_VerRecord, FtpBLL ftpBLL)
        {
            ZipHelper zipHelper = new ZipHelper();
            exeZip = zipHelper.CompressDirectory(basePath, files, mX_VerRecord.AppName + mX_VerRecord.Version, 6, false, uiBLL,30);
            List<string> pahts = new List<string>() { exeZip };
            return ftpBLL.FileUpLoad(pahts, folder, mX_VerRecord,uiBLL, false);
        }
        public bool UpCodeZip(string folder, Sql3Helper.MX_AppVerRecord mX_VerRecord, FtpBLL ftpBLL)
        {
            ZipHelper zipHelper = new ZipHelper();
            codeZip = zipHelper.CompressDirectory(basePath, files, mX_VerRecord.AppName + mX_VerRecord.Version+"(code)", 6, false, uiBLL,25);
            exeZip = zipHelper.CompressDirectory(exeBasePath, exeFiles, mX_VerRecord.AppName + mX_VerRecord.Version, 6, false, uiBLL, 5);
            List<string> pahts = new List<string>() { codeZip, exeZip };
            return ftpBLL.FileUpLoad(pahts, folder, mX_VerRecord, uiBLL, true);
        }
        #endregion

        #region 推送
        private DingTalkDAL dingTalk = new DingTalkDAL();
        private void BtnPush_Click(object sender, RoutedEventArgs e)
        {
            //if (TbxMsg.Text == "" || TbxNames.Text == "")
            //{
            //    ShowMessage("提示！", "请先完善推送信息！");
            //    return;
            //}
            //bool? dialog = ShowMessage("推送消息确认！", TbxMsg.Text);
            //if (dialog == true)
            //{
            //    try
            //    {
            //        string[] names = TbxNames.Text.Split(';');
            //        foreach (var name in names)
            //        {
            //            if (name != "")
            //            {
            //                string userid = dingTalk.GetUserID(name);
            //                //todo 推送接口
            //            }
            //        }
            //    }
            //    catch (Exception ee)
            //    {
            //        ShowMessage("错误！", ee.ToString());
            //        LogHelper.WriteLog(ee.ToString());
            //        return;
            //    }

            //}
        }

        private void CbxWorkPlace_DropDownOpened(object sender, EventArgs e)
        {
           // CbxWorkPlace.ItemsSource = dingTalk.GetWorkPlaces();
        }

        private void CbxWorkPlace_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           // CbxUserName.Text = "";
        }

        private void CbxUserName_DropDownOpened(object sender, EventArgs e)
        {
            //if (CbxWorkPlace.Text != "")
            //{
            //    CbxUserName.ItemsSource = dingTalk.GetUserNames(CbxWorkPlace.Text);
            //}
        }
        private void CbxUserName_DropDownClosed(object sender, EventArgs e)
        {
            //if (CbxUserName.Text != "" && !TbxNames.Text.Contains(CbxUserName.Text))
            //{
            //    TbxNames.Text += (CbxUserName.Text + ";");
            //}
        }

        #endregion

        private void CbCode_Checked(object sender, RoutedEventArgs e)
        {
            exePath = "";
            CbFile.IsChecked = false;
            configFiles.Clear();
            TreeGrid.Children.Clear();
            TreeGrid.Children.Add(new SourceTreeView(this));
        }

        private void CbCode_Unchecked(object sender, RoutedEventArgs e)
        {
            exePath = "";
            configFiles.Clear();
            TreeGrid.Children.Clear();
            TreeGrid.Children.Add(TreeBorder);
        }

        private void CbFile_Checked(object sender, RoutedEventArgs e)
        {
            CbCode.IsChecked = false;
        }

        private void CbFile_Unchecked(object sender, RoutedEventArgs e)
        {

        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            names = shenPiDAL.GetPushUsers((sender as System.Windows.Controls.ComboBox).SelectedItem.ToString());
            ObservableCollection<User> users = new ObservableCollection<User>();
            foreach (var name in names)
            {
                var user = new User { Name = name };
                if (pushUsers.Contains(name))
                {
                    user.Check = true;
                }
                users.Add(user);
            }
            viewModel.PushUsers = users;
        }


        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            TextBoxName.Focus();
            TextBoxName.SelectAll();
        }

        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            var name =(sender as System.Windows.Controls.CheckBox).Content.ToString();
            if (pushUsers.Contains(name) == false)
            {
                pushUsers.Add(name);
                var tag = new HandyControl.Controls.Tag();
                tag.Content = name;
                tag.Closed += Tag_Closed;
                WrapPanelNames.Children.Add(tag); 
            }
            TextBoxName.Focus();
            TextBoxName.SelectAll();
        }

        private void Tag_Closed(object sender, EventArgs e)
        {
            string name = (sender as HandyControl.Controls.Tag).Content.ToString();
            for (int i = 0; i < WrapPanelNames.Children.Count; i++)
            {
                var tag = WrapPanelNames.Children[i] as HandyControl.Controls.Tag;
                if (tag?.Content.ToString() == name)
                {
                    WrapPanelNames.Children.Remove(tag);
                }
            }
            var user = viewModel.PushUsers.FirstOrDefault(it => it.Name == name);
            if (user != null)
            {
                user.Check = false;
            }
            pushUsers.Remove(name);
            TextBoxName.Focus();
            TextBoxName.SelectAll();
        }

        private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
        {
            var name = (sender as System.Windows.Controls.CheckBox).Content.ToString();
            for (int i = 0; i < WrapPanelNames.Children.Count; i++)
            {
                var tag = WrapPanelNames.Children[i] as HandyControl.Controls.Tag;
                if (tag?.Content.ToString() == name)
                {
                    WrapPanelNames.Children.Remove(tag);
                }
            }
            pushUsers.Remove(name);
            TextBoxName.Focus();
            TextBoxName.SelectAll();

        }

        private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
        {
            string txt = TextBoxName.Text;
            ObservableCollection<User> users = new ObservableCollection<User>();
            foreach (var name in names)
            {
                if (txt.Length == 0)
                {
                    var user = new User { Name = name };
                    if (pushUsers.Contains(name))
                    {
                        user.Check = true;
                    }
                    users.Add(user);
                }
                else
                {
                    if (Regex.IsMatch(txt, @"[\u4e00-\u9fa5]"))
                    {
                        if (name.StartsWith(txt))
                        {
                            var user = new User { Name = name };
                            if (pushUsers.Contains(name))
                            {
                                user.Check = true;
                            }
                            users.Add(user);
                        }
                    }
                }

            }
            viewModel.PushUsers = users;
        }

        private void Expander_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TextBoxName.Focus();
            TextBoxName.SelectAll();

        }

        private void ExpanderNames_LostFocus(object sender, RoutedEventArgs e)
        {
            if (ItemList.IsMouseOver==false)
            {
                ExpanderNames.IsExpanded = false;
            }
        }

        private void ExpanderNames_GotFocus(object sender, RoutedEventArgs e)
        {
            ExpanderNames.IsExpanded = false;
        }

        private void TextBoxName_GotFocus(object sender, RoutedEventArgs e)
        {
            if (ExpanderNames.IsExpanded == false)
            {
                ExpanderNames.IsExpanded = true;
            }
        }

        private void PackIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                FolderHelper dialog = new FolderHelper();
                if (dialog.ShowDialog(((HwndSource)PresentationSource.FromVisual(this)).Handle) == true)
                {
                    viewModel.GuDingLuJing = dialog.FileName;
                }
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
                LogHelper.WriteLog(ee.ToString());
            }
        }

        private void WrapPanelNames_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            cbb.Height = WrapPanelNames.ActualHeight + 12;
        }
    }
}
